<?php
namespace Novel\Controller;


use Com\Weixin\WeixinService;
use Novel\Model\UserModel;
use Org\Util\JWT;
use Think\Controller\RestController;

class ControllerBase extends RestController
{
    protected $uid = 1000000;
    public function __construct($flag = true)
    {
        if($flag){
            $oid = I('oid');
            $token = I('token');
            if(empty($token)) {
                $union_id = session('union_id');
                if ($oid && !$union_id) {
                    $data = I('data');
                    $union_id = (new UserModel())->getUnionIdByOpenid($oid, $data);
                    session('union_id', $union_id);
                    session('data', $data);
                    $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                    redirect( $url);
                } else {
                    if ($union_id) {
                        $this->uid = (new UserModel())->getUidByUnionId($union_id);
                    } else {
                        $this->auth();
                    }
                }
            }else{
                try{
                    $this->uid = $this->getUid($token);
                }catch (\Exception $e){
                    $this->uid = false;
                }
            }
            parent::__construct();
            if(!$this->uid){
                if(IS_AJAX){
                    $res = ['status'=>1001,'msg'=>'登录验证失败','data'=>[]];
                    $this->response($res);
                }else{
                    $this->display('error/403');
                    exit;
                }
            }else{
                $token = JWT::encode($this->uid.':'.time(),C("SECRET_KEY"),"HS256");
                $this->assign('token',$token);
                $this->assign('uid',$this->uid);
            }
        }else{
            parent::__construct();
        }
    }

    //获取openid
    private function auth(){
//        $request_url = 'http://uc.hufumiaozhao.hivideocom.com/';//护肤妙招
        $request_url = 'http://uc.lvsehuamushenlin.ylxfz.com';//绿色花木森林
        $auth = new WeixinService('namestc','362243065982a545e050047fcf3af615',$request_url);
        $auth->auth(urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']),'snsapi_base');
    }

    public function _empty()
    {
        $data = array();
        $data['status'] = 404;
        $data['msg'] = 'action not found';
        
        $this->response($data, 'json');
    }
    /**
     * 输出返回数据
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type 返回类型 JSON XML
     * @param integer $code HTTP状态
     * @return void
     */
    protected function response($data, $type = 'json', $code = 200)
    {
//         header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept');
        $this->sendHttpStatus($code);
        exit($this->encodeData($data, strtolower($type)));
    }

    /**
     * 通过token获取用户的uid
     */
    protected function getUid($token){
        if(empty($token)){
            return false;
        }
        $token = explode(":",JWT::decode($token,C('SECRET_KEY'),array('HS256')));
        if(time()-$token[1] > 24*3600){
            return false;
        }else{
            return intval($token[0]);
        }


    }
    /**
     * 通过token获取用户的openid
     */
    protected function getOid($token){
        if(empty($token)){
            return false;
        }
        $token = explode(":",JWT::decode($token,C('SECRET_KEY'),array('HS256')));
        if(time()-$token[1] > 24*3600){
            return false;
        }else{
            return $token[0];
        }


    }

    /**
     * 网页授权
     * @param string $backUrl
     * @param string $scope
     */
    private function toAuth($backUrl = '',$scope = "snsapi_base"){
        if(empty($backUrl)){
            $backUrl = $this->curPageURL();
        }
        $appId = C('AppID');
        $secret = C('AppSecret');
        $backUrl = urlencode($backUrl);
        // 去微信授权，当没有code的时候，现在获取code
        if(!isset($_GET['code'])){
            $getCode ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$backUrl&response_type=code&scope=$scope&state=STATE#wechat_redirect";
            redirect($getCode);
            exit();
        }else{
            $code = I('code');
            $getopenid = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$secret&code=$code&grant_type=authorization_code";
            $getdata = https_request($getopenid);
            $getopenid = json_decode($getdata,true);
            $openid = $getopenid['openid'];
            $o_token = JWT::encode($openid.':'.time(),C("SECRET_KEY"),"HS256");
            $backUrl = urldecode($backUrl);
            $backUrl = $backUrl.(strpos($backUrl,'?')?'&':'?')."o_token=".$o_token;
            header("Location:".$backUrl);
            exit();
        }
    }
    /**
     * 说明：获取完整URL
     */
    private function curPageURL(){
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }
    /* end of base controller */
}